<template>
  <div></div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { isFirstLogin, wxLogin, wxOpenId, wxEmpower } from '@/api/login';
import { getConfig } from '@/api/personalCenter'
import { showToast } from 'vant';

const router = useRouter()

//  获取 code 
const handleLoagin = async () => {
  localStorage.setItem('ooo', '111');
  const params = location.search;
  let openId = localStorage.getItem('openId'); //  openId 存在才执行下面的

  //  说明当前是微信登录页
  if (params.includes('code=')) {
    const code = window.location.search.substring(6).split('&')[0];
    //  获取 设置 code
    await getOpenId({ code });
    openId = localStorage.getItem('openId');
  } else {  //  判断 token是否过期，如果过期则重新进行请求
    if (!openId) await wxEmpower();  // 跳转微信登录页，针对第一次登录
  }

  if (openId) {
    //  判断用户是否是首次登录
    await handleIsFirstLogin(openId);
  }
}

//  判断是否是首次登录
const handleIsFirstLogin = async (openId) => {
  const { code, data } = await isFirstLogin({ openId });
  if (code == 200) {
    if (data && data.length > 0) {
      try {
        localStorage.setItem('parentId', JSON.stringify(data[0].parentId));
        localStorage.setItem('userInfo', JSON.stringify(data));
      } catch (ev) { }

      try {
        const { mobilePhone, openId, realName } = JSON.parse(localStorage.getItem('userInfo'))[0];
        //  判断当前用户是否登录
        await resolveToken({ mobilePhone, openId, realName });
      } catch (ev) { }
    } else {
      //  调整页面 让用户输入内容
      router.push({ path: '/InformationCollection' })
    }
  }
}

//  获取并设置 token
const resolveToken = async (obj) => {
  if (!localStorage.getItem('token')) {
    //  登录 获取 token
    const { code, data } = await wxLogin({
      grant_type: 'wechat',
      phoneNumber: obj.mobilePhone,
      openId: obj.openId,
      name: obj.realName,
      client_id: 'admin',
      client_secret: '123456',
      timestamp: '1713495821000',
      orgId: '550655738519750597'
    });

    if (code === 200) {
      const token = data.token;
      if (token) {
        localStorage.setItem('token', token);
        clearVideoUrl();
        //  登录成功 跳转到首页
        router.push({ path: '/Home' });
      }
    }
  } else {
    clearVideoUrl();
    //  token 存在 跳转回首页
    router.push({ path: '/Home' });
  }
}

//  清除 原来的 video_url
function clearVideoUrl() {
  const video_url = localStorage.getItem('video_url');
  if (video_url) {
    localStorage.removeItem('video_url');
  }
}

//  获取 openid
const getOpenId = async (options) => {
  const { code, data } = await wxOpenId(options); //  获取 openId
  if (code === 200) {
    //  将 openId 进行缓存 
    localStorage.setItem('openId', data.openid);
  }
}

//获取全局配置
const getConfigList = () => {
  const params = {
    currentPage: 1,
    pageSize: 20
  }
  getConfig(params).then((res) => {
    if (res.code === 200) {
      if (res.data.list.length != 0) {
        const { scoreLowerLimit, fillStartTime, fillEndTime } = res.data.list[0]
        localStorage.setItem('scoreLowerLimit', scoreLowerLimit);
        localStorage.setItem('fillStartTime', fillStartTime);
        localStorage.setItem('fillEndTime', fillEndTime);
      } else { }
    } else {
    }
  }).catch((err) => {
    console.log(err)
  })
}

onMounted(() => {
  console.log('ooo');
  handleLoagin();
  getConfigList()
})



</script>
<style scoped lang='scss'></style>